package com.simplenix.nicasio.admin.mb;

import com.simplenix.nicasio.hmaint.HMaintException;
import com.simplenix.nicasio.hmaint.util.HMaintUtil;
import com.simplenix.nicasio.mb.Session;
import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.Conventions;
import com.simplenix.nicasio.misc.Internationalization;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.persistence.HibernateUtil;
import javax.faces.context.FacesContext;
import org.hibernate.Criteria;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;

/**
 *
 * @author fronald
 */
public class User extends com.simplenix.nicasio.admin.eb.User {

	/** Creates a new instance of User */
	public User() {
	}

	public User getLoggedUser() {
		com.simplenix.nicasio.admin.eb.User u = (com.simplenix.nicasio.admin.eb.User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(Session.CURRENT_USER);
		this.setEmail(u.getEmail());
		this.setLogin(u.getLogin());
		this.setName(u.getName());
		this.setPassword(u.getPassword());
		this.setUsuId(u.getUsuId());
		return this;
	}

	public String save() throws HMaintException {
		Transaction t = HibernateUtil.getCurrentSession().getTransaction();
		if (!t.isActive()) {
			t.begin();
		}
		com.simplenix.nicasio.admin.eb.User u = (com.simplenix.nicasio.admin.eb.User) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(Session.CURRENT_USER);
		u = (com.simplenix.nicasio.admin.eb.User) HMaintUtil.findById(com.simplenix.nicasio.admin.eb.User.class, Long.toString(u.getUsuId()));
		u.setEmail(this.getEmail());
		if (!StrUtil.nvl(u.getPassword()).equals(this.getPassword())) {
			u.setPassword(User.encriptPassword(this.getPassword()));
		}
		HibernateUtil.getCurrentSession().merge(u);
		t.commit();
		return "Y";
	}

	public String doLogin() {
		String rtn = Conventions.NO;
		Transaction t = HibernateUtil.getCurrentSession().beginTransaction();
		Criteria c = HibernateUtil.getCurrentSession().createCriteria(com.simplenix.nicasio.admin.eb.User.class);
		c.add(Restrictions.eq("login", this.getLogin()));
		com.simplenix.nicasio.admin.eb.User u = (com.simplenix.nicasio.admin.eb.User) c.uniqueResult();
		if (u != null) {
			String passwd = User.encriptPassword(this.getPassword());
			if (passwd.equals(u.getPassword())) {
				this.setEmail(u.getEmail());
				this.setLogin(u.getLogin());
				this.setName(u.getName());
				this.setUsuId(u.getUsuId());
				FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(Session.CURRENT_USER, u);
				rtn = Conventions.YES;
			}
		}
		if (rtn.equals(Conventions.NO)) {
			try {
				FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(Session.FLASH_MESSAGE, Internationalization.getInstance().getString("login.wrong"));
			} catch (AppException e) {
				e.printStackTrace();
			}
		}
		t.commit();
		return rtn;
	}

}
